import random

import misaka as m
import mistune
from pygments import highlight
from pygments.formatters.html import HtmlFormatter
from pygments.lexers import get_lexer_by_name

from view.MarkdownRender.URLParser import URLParser


class BleepRenderer(m.HtmlRenderer):
    def __init__(self, qiniu_url, base_path):
        super(BleepRenderer, self).__init__()
        self.base_path = base_path[1:]
        self.qiniu_url = qiniu_url + "%2f"

    def image(self, link, title='', alt=' '):
        # rand = str(random.random())
        rand = 1
        link = link.encode('utf8')
        title = title.encode('utf8')
        alt = alt.encode('utf8')
        qiniu = self.qiniu_url.encode('utf8')

        if link.startswith('http:') or link.startswith('https:') or link.startswith('//'):
            pass
        else:
            print 'link1:', link
            link = URLParser.simplifyPath(link)
            if link.startswith('/'):
                link = '%s%s' % (
                    qiniu,
                    link[1:],
                )
            else:
                link = '%s%s%s' % (
                    qiniu,
                    self.base_path,
                    link,
                )
            print 'link2:', link
        text = '<br><img src="%s?v=%s" title="%s" alt="%s" %s/>' % (
            link, rand, title, alt, '')  # data-uk-scrollspy="{cls:\'uk-animation-fade\'}"
        text = '<a href="%s" title="%s" data-uk-lightbox="{group:\'group1\'}">%s</a>' % (
            link, title, text
        )
        text = text.decode('utf8', errors='ignore')

        return text

    def blockcode(self, text, lang):

        if not lang:
            return '\n<pre><code>%s</code></pre>\n' % mistune.escape(text.strip())
        # if not lang:
        #     return u'<br><pre><code>{}</code></pre>'.format(text.strip())

        lexer = get_lexer_by_name(lang, stripall=True)
        formatter = HtmlFormatter(style='monokai')  # linenos='outline',
        html = highlight(text, lexer, formatter)
        return u"%s" % html

    def header(self, content, level):
        if level < 3:
            return u'<h%s id="%s">%s</h%s>' % (level, content, content, level)
        else:
            return u'<h%s>%s</h%s>' % (level, content, level)

    def link(self, content, link, title=''):
        return u'<a href="%s" title="%s" target="_blank">%s</a>' % (link, title, content)
        #
        # def wrap(self, source, outfile):
        #     return self._wrap_code(source)

        # def _wrap_code(self, source):
        #     for i, t in source:
        #         if i == 1:
        #             # it's a line of formatted code
        #             t = '<span class="wrapLineNo"></span>' + t
        #         yield i, t
